package com.phy.kim.Leetcode;

/**
 * Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() {}
 * ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val;
 * this.next = next; } }
 * @author RiceDoggyRoll
 */

public class Leetcode0001AddTwoNumbers {

  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    //创建listnode会把val声明为0，切忌！
    if (l1 == null) {
      return l2;
    }
    if (l2 == null) {
      return l1;
    }
    ListNode res = null;
    ListNode resTemp = null;
    int nextNum = 0;
    while (l1 != null || l2 != null) {
      int n1 = l1 == null ? 0 : l1.val;
      int n2 = l2 == null ? 0 : l2.val;
      int sum = n1 + n2 + nextNum;
      if (res == null) {
        res = resTemp = new ListNode(sum % 10);
      } else {
        resTemp.next = new ListNode(sum % 10);
        resTemp = resTemp.next;
      }
      nextNum = sum / 10;
      if (l1 != null) {
        l1 = l1.next;
      }
      if (l2 != null) {
        l2 = l2.next;
      }
    }
    if (nextNum > 0) {
      resTemp.next = new ListNode(nextNum);
    }
    return res;
  }

  public class ListNode {

    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
      this.val = val;
    }

    ListNode(int val, ListNode next) {
      this.val = val;
      this.next = next;
    }
  }
}